import React, { useEffect, useState } from 'react'
import { Button, Checkbox, Form, Input, InputNumber, message, Modal, Space, Spin, Table, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableDataV2'
import {
  exportQuotationOrderQuotationOrder,
  getIntentOrderDetail,
  getPageQuotationOrderList,
  getQuotationOrderColorRange,
  getQuotationOrderStatusCount,
  getSimpleListBySearchName,
  rejectOrConfirmQuotation,
  splitColor,
  submitNegotiatePrice,
} from '@/api/goods'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useColumns, useOrderQtyColumns } from './TableColumns'
import { ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { getProductClassConfigByType } from '@/api/goods'
import PermissionButton from '@/components/PermissionButton'
import { useAppSelector } from '@/store/hooks'
import { searchConfig } from './FormConfig'
import { exportNotification, getRecentMonths } from '@/utils/util'
import useCachePage from '@/hooks/useCachePage'
import { applicationTypeEnum, OperationLogType } from '@/constant'
import useViewLogs from '@/hooks/useViewLogs'
import LogsDrawer from '@/components/LogsDrawer'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
import useSearchFabric from '@/hooks/useSearchFabric'
import './index.less'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { EditFormVertical } from '@/components/CustomForm'
import useModal from '@/hooks/useModal'
import { UploadOutlined } from '@ant-design/icons'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const [orderNum, setorderNum] = useState<{
    negotiateCount: number
    waitCheckCount: number
    waitQuotationCount: number
  }>({
    negotiateCount: 0,
    waitCheckCount: 0,
    waitQuotationCount: 0,
  })
  const navigate = useNavigate()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [form] = useForm()
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [selectedRowInfos, setselectedRowInfos] = useState<ITableData[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [colorOptions, setcolorOptions] = useState<IOptionItem[]>([])
  const { setCachePage, getCachePage } = useCachePage()
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const { FabricOption, setFabricOption, handleSearchFabric } = useSearchFabric('fabricCode')
  const [mllChecked, setmllChecked] = useState(false)
  const [exportLoading, setexportLoading] = useState(false)
  const [spinning, setspinning] = useState(false)
  const ProDevSeason = useGetProDevSeason()
  const defaultDateRange = getRecentMonths()
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'quotationOrderId',
    OperationLogType.QUOTATION_ORDER,
  )
  const orderQtyModal = useModal()
  const [query] = useSearchParams()
  const quotationOrderCode = query.get('quotationOrderCode') || ''
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getPageQuotationOrderList, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      createTimeStart: quotationOrderCode ? null : defaultDateRange,
      quotationOrderCode,
    },
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqestParams) => {
      const { selectKey, ...reqParams } = reqestParams
      return {
        ...reqParams,
        createTimeStart:
          reqParams.createTimeStart && reqParams.createTimeStart.length === 2 ? reqParams.createTimeStart[0] : null,
        createTimeEnd:
          reqParams.createTimeStart && reqParams.createTimeStart.length === 2 ? reqParams.createTimeStart[1] : null,
        confirmTimeStart:
          reqParams.confirmTimeStart && reqParams.confirmTimeStart.length === 2 ? reqParams.confirmTimeStart[0] : null,
        confirmTimeEnd:
          reqParams.confirmTimeStart && reqParams.confirmTimeStart.length === 2 ? reqParams.confirmTimeStart[1] : null,
        quotationNegotiateStatusList:
          selectKey && selectKey.length === 2
            ? [1, 0]
            : selectKey?.includes('tobeconfirmed')
            ? [1]
            : selectKey?.includes('tobesubmitted')
            ? [0]
            : null,
        sortBySpu: selectKey?.includes('sortBySpu'),
      }
    },
  })
  useEffect(() => {
    getProductClassConfig()
    handleCacheData()
    getToDoList()
  }, [])
  const getToDoList = async () => {
    const res = await getQuotationOrderStatusCount<{
      negotiateCount: number
      waitCheckCount: number
      waitQuotationCount: number
    }>()
    if (res.code === 200 && res?.data != null) {
      setorderNum(res?.data)
    }
  }
  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectedRowKeys(keys)
    setselectedRowInfos(info)
  }
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    setmllChecked(!!cacheData?.mll)
    if (cacheData == null || quotationOrderCode) {
      await form.validateFields()
      search()
      setCachePage({ ...params })
    } else {
      // 清除掉 defaultFieldsParams: {createTimeStart: defaultDateRange}
      form.resetFields()
      form.setFieldsValue({
        ...cacheData,
      })
      setSpuOptions(cacheData?.SpuOptions || [])
      setSupplierOption(cacheData?.SupplierOption || [])
      setFabricOption(cacheData?.FabricOption || [])
      const { SpuOptions, SupplierOption, FabricOption, ...resetCacheData } = cacheData
      reload({ ...resetCacheData })
    }
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSimpleListBySearchName<{
        spuDevId: number
        spuCode: string
        spuName: string
        designCode: string
      }>({ searchName: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: item.spuName,
              code: item.spuCode,
              value: item.spuDevId,
              designCode: item.designCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const onViewLogs = (info: ITableData) => {
    viewLogs(info)
  }
  const onViewOrderQty = async (info: ITableData) => {
    const res = await getIntentOrderDetail({
      quotationOrderId: info.quotationOrderId,
      quotationOrderCode: info.quotationOrderCode,
    })
    if (res.code == 200 && res.data && res.data.length > 0) {
      orderQtyModal.openModal(res.data)
    }
  }
  const handleGetColorRange = async (info: ITableData) => {
    const res = await getQuotationOrderColorRange({
      quotationOrderId: info.quotationOrderId,
      quotationOrderCode: info.quotationOrderCode,
    })
    const data =
      res?.data?.map((item: any) => {
        return {
          label: item.colorDetailName,
          value: item.colorCode,
        }
      }) || []
    setcolorOptions(data)
    colorModal.openModal(info)
  }
  const colorModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
    },
    onReload: () => {
      reload()
    },
    onFail: (error) => {
      if (error.code === 820000) {
        message.error(error?.msg)
      }
    },
  })
  const debounce = (fn: any, delay: number) => {
    let timeout: ITimeoutType
    return (...set: any) => {
      if (timeout) clearTimeout(timeout)
      timeout = setTimeout(() => {
        fn(...set)
      }, delay)
    }
  }

  return (
    <PageContainer className="goods_quotation_wrap">
      <div className="waittodo_box">
        <div className="wait_main">
          <div className="wm_item">
            <div className="wm_item_title">待报价</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    quotationStatusList: [0],
                  })
                  search()
                  setCachePage({
                    ...form.getFieldsValue(),
                    current: 1,
                    size: params.size,
                  })
                }}
              >
                {orderNum.waitQuotationCount || 0}单
              </Typography.Link>
            </div>
          </div>
          <div className="wm_item">
            <div className="wm_item_title">待核价</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    quotationStatusList: [1],
                  })
                  search()
                  setCachePage({
                    ...form.getFieldsValue(),
                    current: 1,
                    size: params.size,
                  })
                }}
              >
                {orderNum.waitCheckCount || 0}单
              </Typography.Link>
            </div>
          </div>
          <div className="wm_item">
            <div className="wm_item_title">议价中</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    quotationStatusList: [2],
                  })
                  search()
                  setCachePage({
                    ...form.getFieldsValue(),
                    current: 1,
                    size: params.size,
                  })
                }}
              >
                {orderNum.negotiateCount || 0}单
              </Typography.Link>
            </div>
          </div>
        </div>
      </div>
      <SearchForm
        params={params}
        form={form}
        searchConfig={searchConfig({
          DICTDATA,
          classBig,
          SpuOptions,
          handleSearchSpu: handleSearchSpuOptions,
          ProDevSeason,
          SupplierOption,
          handleSearchSupplier,
          FabricOption,
          handleSearchFabric,
          isRoot,
        })}
        onFinish={async () => {
          search()
          setCachePage({
            ...form.getFieldsValue(),
            SpuOptions,
            SupplierOption,
            FabricOption,
            current: 1,
            size: params.size,
          })
          setselectedRowKeys([])
          setselectedRowInfos([])
        }}
        onReset={() => {
          reset()
          setCachePage({ current: 1, size: 10, createTimeStart: defaultDateRange })
          setselectedRowKeys([])
          setselectedRowInfos([])
          setmllChecked(false)
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="BatchSubmitFinalPrice"
                type="primary"
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const data = selectedRowInfos.map((item) => {
                    return {
                      quotationOrderId: item.quotationOrderId,
                      quotationOrderCode: item.quotationOrderCode,
                    }
                  })
                  const res = await submitNegotiatePrice(data).finally(() => {
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                  })
                  if (res.code === 200) {
                    message.success('操作成功')
                    search()
                    getToDoList()
                  }
                }}
              >
                批量提交成交价
              </PermissionButton>
              <PermissionButton
                permission="BatchSubmitDealPrice"
                type="primary"
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const data = selectedRowInfos.map((item) => {
                    return {
                      quotationOrderId: item.quotationOrderId,
                      quotationOrderCode: item.quotationOrderCode,
                      rejectOrConfirm: 1,
                    }
                  })
                  const res = await rejectOrConfirmQuotation(data).finally(() => {
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                  })
                  if (res.code === 200) {
                    message.success('操作成功')
                    search()
                    getToDoList()
                  }
                }}
              >
                批量确认成交价
              </PermissionButton>
              <PermissionButton
                permission="BatchReturnDealPrice"
                type="primary"
                danger
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const data = selectedRowInfos.map((item) => {
                    return {
                      quotationOrderId: item.quotationOrderId,
                      quotationOrderCode: item.quotationOrderCode,
                      rejectOrConfirm: 0,
                    }
                  })
                  const res = await rejectOrConfirmQuotation(data).finally(() => {
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                  })
                  if (res.code === 200) {
                    message.success('操作成功')
                    search()
                    getToDoList()
                  }
                }}
              >
                批量驳回成交价
              </PermissionButton>
              <Form form={form} className="suggestion_form">
                <Form.Item noStyle name="selectKey">
                  <Checkbox.Group
                    onChange={(selectKey) => {
                      const cacheData = getCachePage()
                      setCachePage({
                        ...cacheData,
                        selectKey,
                        // 只要search那么current肯定是1 current肯定是1
                        current: 1,
                      })
                      search()
                    }}
                    options={[
                      {
                        label: '只看议价待确认',
                        value: 'tobeconfirmed',
                      },
                      {
                        label: '只看议价待提交',
                        value: 'tobesubmitted',
                      },
                      {
                        label: '按款排序展示',
                        value: 'sortBySpu',
                      },
                    ]}
                  />
                </Form.Item>
                {/* {isRoot && (
                  <Form.Item noStyle name="mll">
                    <div className="flex_center">
                      <Checkbox checked={mllChecked} disabled></Checkbox>
                      <span>只看毛利率低于</span>
                      <InputNumber
                        min={1}
                        max={100}
                        precision={2}
                        autoFocus
                        defaultValue={getCachePage()?.mll || null}
                        style={{ width: 94 }}
                        addonAfter="%"
                        onChange={debounce((value: any) => {
                          console.log(3333)
                          const val = Math.round(Number(value) * 100) / 100
                          setmllChecked(val != 0)
                          const cacheData = getCachePage()
                          setCachePage({
                            ...cacheData,
                            mll: val == 0 ? null : val,
                            current: 1,
                          })
                          search()
                        }, 1000)}
                      ></InputNumber>
                    </div>
                  </Form.Item>
                )} */}
              </Form>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="ExportQuotationList"
                onClick={async () => {
                  const paramsData: Record<string, any> = {}
                  if (selectedRowKeys.length > 0) {
                    paramsData.quotationOrderIds = selectedRowKeys
                  } else {
                    Object.assign(paramsData, params)
                  }
                  setexportLoading(true)
                  setspinning(true)
                  const res = await exportQuotationOrderQuotationOrder(paramsData)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setexportLoading(false)
                      setselectedRowKeys([])
                      setselectedRowInfos([])
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
                icon={<UploadOutlined />}
                loading={exportLoading}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        className="small_sise_customtable"
        bordered
        columns={useColumns({
          navigate,
          handleGetColorRange,
          onViewLogs,
          onViewOrderQty,
          isRoot,
          SplitColor: buttonCodeList?.includes('SplitColor'),
        })}
        {...tableProps}
        rowKey={(rows) => rows.quotationOrderId}
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        isScrollY
        extraHeight={86}
      />
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <Modal
        title="分色"
        open={colorModal.open}
        maskClosable
        onCancel={colorModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={colorModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={colorModal.confirmLoading}
                onClick={() =>
                  colorModal.handleSubmit((vals: any) => {
                    const colorList = colorOptions
                      ?.filter((item: any) => vals?.colorList?.includes(item.value))
                      ?.map((item) => {
                        return {
                          colorDetailName: item.label,
                          colorCode: item.value,
                        }
                      })
                    return splitColor({
                      colorList,
                      quotationOrderId: colorModal.currentRecord.quotationOrderId,
                      quotationOrderCode: colorModal.currentRecord.quotationOrderCode,
                    })
                  })
                }
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              label: '请勾选需要单独报价的款式色',
              name: 'colorList',
              type: 'Checkbox',
              option: colorOptions,
              placeholder: '请勾选需要单独报价的款式色',
              rules: [
                {
                  required: true,
                  message: '请勾选需要单独报价的款式色',
                },
              ],
            },
          ]}
          form={colorModal.form}
        />
      </Modal>
      <Modal
        width={1200}
        title="关联订单明细"
        footer={null}
        open={orderQtyModal.open}
        maskClosable
        onCancel={orderQtyModal.closeModal}
      >
        <div className="custom_table_style">
          <Table
            bordered
            columns={useOrderQtyColumns()}
            dataSource={orderQtyModal.currentRecord || []}
            rowKey="intentOrderCode"
            scroll={{ y: 400 }}
            pagination={false}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
          />
        </div>
      </Modal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
